<?php 
defined('BASEPATH') OR exit('No direct script access allowed');
require_once FCPATH.'/ctcms/libs/phpTree.php';
class Comments extends Ctcms_Controller{
	function __construct(){

	    parent::__construct();

	}

	public function index()

	{
		 $pageNo=$_GET["pageNo"]?$this->input->get("pageNo"):1;
		 $pageSize=$_GET["pageSize"]?$this->input->get("pageSize"):10;
		 $limit=(($pageNo-1)*$pageSize).",".$pageSize;
		// $where="";
		 $where['parent_id']=empty($this->input->get("parent_id"))?"0":$this->input->get("parent_id")."";
		 $where["play_id"]=$this->input->get("play_id");
		 $arr=$this->csdb->get_select('comment','*',$where,'id DESC',$limit);
		 $arr=json_decode(json_encode($arr),true);//要吐血的这一步
		
		 foreach ($arr as $key => $value) {
		 	$where["parent_id"]=$value["id"];
		 	$arrC=json_decode(json_encode($this->csdb->get_select('comment','*',$where,'id DESC',$limit)),true);
             $arr=array_merge($arr,$arrC);

		 }
		 foreach($arr as $key=>$item){
           $user_id=$item["user_id"];
           $whereC["id"]=$user_id;
           $user=json_decode(json_encode($this->csdb->get_select('user','*',$whereC)),true);
           $item["user"]=$user[0];
           $whereM["comment_id"]=$item["id"];
           $whereM["user_id"]=$_GET["user_id"]?$GET["user_id"]:0;
           $mutual=json_decode(json_encode($this->csdb->get_nums('mutual','*',$whereM)),true);
           if($mutual!=0){
           	$item["isPraised"]=1;
           }else{
           	$item["isPraised"]=0;
           }

           $arr[$key]=$item;
		 }
         $r = PHPTree::makeTree($arr);
		echo json_encode($r);
    }

    public function save()

	{

		if($_SERVER['REQUEST_METHOD']!="POST"){
    		echo '{"status":0,"msg":"請求方式不對"}';
    		exit();
    	}else{
    		 parse_str(file_get_contents("php://input"), $param);
    		 try{
    		 	$result_id=$this->csdb->get_insert('comment',$param);
    		 	echo '{"status":1,"msg":"添加成功","id":'.$result_id.'}';
                 
            } catch (Exception $e) {
				print $e->getMessage();
				exit();
            }
         }
	}


//点赞
	public function operationPraiseCount(){
		parse_str(file_get_contents("php://input"), $param);
		$paramT["comment_id"]=$param["id"];
		$paramT["user_id"]=$param["user_id"];
		// echo $param["flag"];
		// exit();
		if($param["flag"]=="true"){
			$result_id=$this->csdb->get_insert('mutual',$paramT);
		}else{
			$sql = 'delete from '.CT_SqlPrefix.'mutual where 1=1 and user_id='.$param["user_id"].' and comment_id='.$param["id"];
			// echo $sql;
			// exit();
			$this->parser->CI->db->query($sql);
		}
		
		
        $where["comment_id"]=$param["id"];
		$count=$this->csdb->get_nums('mutual',"*",$where);
		$arr["praise_count"]=$count;
		$result=$this->csdb->get_update('comment',$param["id"],$arr,$zd='id');
		echo '{"status":1,"msg":"操作成功"}';

	}

}